import sys
from PyQt4 import QtCore, QtGui
from lib.papyDB import papyDB#, tableInfo
from lib import papyDBTable
papyDB = papyDB()

class Window(QtGui.QWidget):
    def __init__(self):
        QtGui.QWidget.__init__(self)        
        self.treeView = QtGui.QTreeView()
        self.treeView.setContextMenuPolicy(QtCore.Qt.CustomContextMenu)
        self.treeView.customContextMenuRequested.connect(self.openMenu)

        data = self.data()
        self.model = QtGui.QStandardItemModel()
        self.addItems(self.model, data)
        self.treeView.setModel(self.model)
        self.model.setHorizontalHeaderLabels([self.tr("PAPYRUS")])
        layout = QtGui.QVBoxLayout()
        layout.addWidget(self.treeView)
        self.setLayout(layout)

#    def __del__(self):
#        papyDB.cr.close()
        
    def data(self):
        temp = ''
        data = [ ]
        dataList = [  ]
        prjList = papyDBTable.PROJECT.search('prjName')
        for x in range(len(prjList)):
            seqList = papyDBTable.SEQUENCES.search( 'seqName' , prjID = x+1 )
            for y in range(len(seqList)):
                temp +=', ("' + str(seqList[y]) + '", [])'   
            data.append( temp[2:] )  
            temp = ''        
        for x in range(len(data)):
            temp = '( "' + prjList[x] + '", [' + data[x] + '] )'
            dataList.append(str(temp))
        temp = ''
        for x in range(len(dataList)):
            temp += dataList[x] + ',' 
        returnData = list(eval(temp[:-1]))
        print returnData
        return returnData    

    def addItems(self, parent, elements):
        for text, children in elements:
            item = QtGui.QStandardItem(text)
            parent.appendRow(item)
            if children:
                self.addItems(item, children)

    def openMenu(self, position):
        indexes = self.treeView.selectedIndexes()
        if len(indexes) > 0:
            level = 0
            index = indexes[0]
            while index.parent().isValid():
                index = index.parent()
                level += 1                
        menu = QtGui.QMenu()
        if level == 0:
            menu.addAction(self.tr("Make Project"))
            menu.addAction(self.tr("Add Sequence"))
        elif level == 1:
            menu.addAction(self.tr("Make Sequence"))
            menu.addAction(self.tr("Add Shot"))
        elif level == 2:
            menu.addAction(self.tr("Make Shot"))         
        menu.exec_(self.treeView.viewport().mapToGlobal(position))
      
        
if __name__ == "__main__":
    app = QtGui.QApplication(sys.argv)
    window = Window()
    window.show()
#    window.__del__()
    sys.exit(app.exec_())







        
